package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Product;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.dto.ProductDTO;
import com.zhao.fishingguideserver.service.ProductService;
import com.zhao.fishingguideserver.service.OssService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.math.BigDecimal;

/**
 * 二手渔具商品管理控制器
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    
    @Autowired
    private OssService ossService;

    /**
     * 添加商品（发布二手渔具）- 带文件上传
     */
    @PostMapping("/addWithFiles")
    public Result<String> addProductWithFiles(
            @RequestParam("productName") String productName,
            @RequestParam("productDetail") String productDetail,
            @RequestParam("oldLevel") Integer oldLevel,
            @RequestParam("price") BigDecimal price,
            @RequestParam(value = "files", required = false) MultipartFile[] files) {
        try {
            // 从ThreadLocal获取当前登录用户ID
            Map<String, Object> claims = ThreadLocalUtil.get();
            if (claims == null || claims.get("id") == null) {
                return Result.error("用户未登录");
            }
            Long userId = Long.parseLong(claims.get("id").toString());
            
            // 创建商品对象
            Product product = new Product();
            product.setProductName(productName);
            product.setProductDetail(productDetail);
            product.setOldLevel(oldLevel);
            product.setPrice(price);
            product.setUserId(userId.intValue());
            product.setCreatTime(new Date());
            
            // 处理文件上传
            if (files != null && files.length > 0) {
                List<String> imageUrls = new ArrayList<>();
                String folder = "product-images/";
                
                for (MultipartFile file : files) {
                    if (!file.isEmpty()) {
                        try {
                            String fileUrl = ossService.uploadFile(file, folder);
                            imageUrls.add(fileUrl);
                        } catch (Exception e) {
                            // 记录上传失败的文件，但不中断整个流程
                            System.err.println("文件上传失败: " + file.getOriginalFilename() + ", 错误: " + e.getMessage());
                        }
                    }
                }
                
                // 将图片URL列表转换为逗号分隔的字符串
                if (!imageUrls.isEmpty()) {
                    product.setCoverList(String.join(",", imageUrls));
                }
            }
            
            int result = productService.insert(product);
            return result > 0 ? Result.success("商品发布成功") : Result.error("商品发布失败");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("商品发布失败: " + e.getMessage());
        }
    }

    /**
     * 添加商品（发布二手渔具）- 原有方法保持兼容
     */
    @PostMapping("/add")
    public Result<String> addProduct(@RequestBody Map<String, Object> requestData) {
        try {
            // 从ThreadLocal获取当前登录用户ID
            Map<String, Object> claims = ThreadLocalUtil.get();
            if (claims == null || claims.get("id") == null) {
                return Result.error("用户未登录");
            }
            Long userId = Long.parseLong(claims.get("id").toString());
            
            // 创建商品对象
            Product product = new Product();
            
            // 处理商品名称（可能是数组格式）
            Object productNameObj = requestData.get("productName");
            if (productNameObj instanceof java.util.List) {
                java.util.List<?> productNameList = (java.util.List<?>) productNameObj;
                if (!productNameList.isEmpty()) {
                    product.setProductName(productNameList.get(0).toString());
                }
            } else if (productNameObj != null) {
                product.setProductName(productNameObj.toString());
            }
            
            // 处理商品详情
            Object productDetailObj = requestData.get("productDetail");
            if (productDetailObj != null) {
                product.setProductDetail(productDetailObj.toString());
            }
            
            // 处理商品图片（可能是数组格式）
            Object coverListObj = requestData.get("coverList");
            if (coverListObj instanceof java.util.List) {
                java.util.List<?> coverListArray = (java.util.List<?>) coverListObj;
                if (!coverListArray.isEmpty()) {
                    // 将图片数组转换为逗号分隔的字符串
                    StringBuilder coverListStr = new StringBuilder();
                    for (int i = 0; i < coverListArray.size(); i++) {
                        if (i > 0) {
                            coverListStr.append(",");
                        }
                        coverListStr.append(coverListArray.get(i).toString());
                    }
                    product.setCoverList(coverListStr.toString());
                }
            } else if (coverListObj != null) {
                product.setCoverList(coverListObj.toString());
            }
            
            // 处理新旧程度
            Object oldLevelObj = requestData.get("oldLevel");
            if (oldLevelObj != null) {
                if (oldLevelObj instanceof Number) {
                    product.setOldLevel(((Number) oldLevelObj).intValue());
                } else {
                    product.setOldLevel(Integer.parseInt(oldLevelObj.toString()));
                }
            }
            
            // 处理价格
            Object priceObj = requestData.get("price");
            if (priceObj != null) {
                if (priceObj instanceof Number) {
                    product.setPrice(new BigDecimal(priceObj.toString()));
                } else {
                    product.setPrice(new BigDecimal(priceObj.toString()));
                }
            }
            
            // 设置商品发布者和创建时间
            product.setUserId(userId.intValue());
            product.setCreatTime(new Date());
            
            int result = productService.insert(product);
            return result > 0 ? Result.success("商品发布成功") : Result.error("商品发布失败");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("商品发布失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有商品（商品列表页）
     */
    @GetMapping("/list")
    public Result<List<ProductDTO>> selectAll() {
        List<Product> products = productService.selectAll();
        List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
        return Result.success(productDTOs);
    }

    /**
     * 查询所有商品（保持兼容旧接口）
     */
    @GetMapping("/selectAll")
    public Result<List<ProductDTO>> selectAllLegacy() {
        List<Product> products = productService.selectAll();
        List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
        return Result.success(productDTOs);
    }

    /**
     * 查询所有在售商品（前端首页展示 - 推荐使用）
     * 只显示状态为 'available' 的商品
     */
    @GetMapping("/available")
    public Result<List<ProductDTO>> selectAvailable() {
        try {
            List<Product> products = productService.selectAvailable();
            List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
            return Result.success(productDTOs);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询商品失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询商品详情
     */
    @GetMapping("/detail/{id}")
    public Result<ProductDTO> getProductDetail(@PathVariable Long id) {
        Product product = productService.selectByPrimaryKey(id);
        if (product == null) {
            return Result.error("商品不存在");
        }
        ProductDTO productDTO = ProductDTO.fromProduct(product);
        return Result.success(productDTO);
    }

    /**
     * 更新商品信息（仅商品发布者可以修改）
     */
    @PutMapping("/update")
    public Result<String> updateProduct(@RequestBody Product product) {
        // 验证用户是否为商品发布者
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());

        // 查询原商品信息
        Product existProduct = productService.selectByPrimaryKey(product.getProductId());
        if (existProduct == null) {
            return Result.error("商品不存在");
        }
        if (!existProduct.getUserId().equals(userId.intValue())) {
            return Result.error("无权修改他人发布的商品");
        }

        int result = productService.updateByPrimaryKeySelective(product);
        return result > 0 ? Result.success("商品更新成功") : Result.error("商品更新失败");
    }

    /**
     * 删除商品（仅商品发布者可以删除）
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteProduct(@PathVariable Long id) {
        // 验证用户是否为商品发布者
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());

        // 查询商品信息
        Product existProduct = productService.selectByPrimaryKey(id);
        if (existProduct == null) {
            return Result.error("商品不存在");
        }
        if (!existProduct.getUserId().equals(userId.intValue())) {
            return Result.error("无权删除他人发布的商品");
        }

        int result = productService.deleteByPrimaryKey(id);
        return result > 0 ? Result.success("商品删除成功") : Result.error("商品删除失败");
    }

    /**
     * 根据用户ID查询商品（我的发布）
     */
    @GetMapping("/myProducts")
    public Result<List<ProductDTO>> getMyProducts() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());
        
        List<Product> products = productService.selectByUserId(userId.intValue());
        List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
        return Result.success(productDTOs);
    }

    /**
     * 根据条件搜索商品
     */
    @GetMapping("/search")
    public Result<List<ProductDTO>> searchProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer minPrice,
            @RequestParam(required = false) Integer maxPrice,
            @RequestParam(required = false) Integer oldLevel
    ) {
        List<Product> products = productService.searchProducts(keyword, minPrice, maxPrice, oldLevel);
        List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
        return Result.success(productDTOs);
    }

    /**
     * 根据新旧程度筛选商品
     */
    @GetMapping("/filterByOldLevel/{oldLevel}")
    public Result<List<ProductDTO>> filterByOldLevel(@PathVariable Integer oldLevel) {
        List<Product> products = productService.selectByOldLevel(oldLevel);
        List<ProductDTO> productDTOs = ProductDTO.fromProductList(products);
        return Result.success(productDTOs);
    }
    
    /**
     * 上传商品图片
     */
    @PostMapping("/uploadImages")
    public Result<Map<String, Object>> uploadProductImages(@RequestParam("files") MultipartFile[] files) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<String> imageUrls = new ArrayList<>();
            List<String> failedFiles = new ArrayList<>();
            String folder = "product-images/";
            
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        // 验证文件类型
                        String contentType = file.getContentType();
                        if (contentType == null || !contentType.startsWith("image/")) {
                            failedFiles.add(file.getOriginalFilename() + " (不是图片文件)");
                            continue;
                        }
                        
                        // 验证文件大小 (限制为5MB)
                        if (file.getSize() > 5 * 1024 * 1024) {
                            failedFiles.add(file.getOriginalFilename() + " (文件过大，超过5MB)");
                            continue;
                        }
                        
                        String fileUrl = ossService.uploadFile(file, folder);
                        imageUrls.add(fileUrl);
                        
                    } catch (Exception e) {
                        failedFiles.add(file.getOriginalFilename() + " (" + e.getMessage() + ")");
                    }
                }
            }
            
            result.put("successUrls", imageUrls);
            result.put("failedFiles", failedFiles);
            result.put("totalCount", files.length);
            result.put("successCount", imageUrls.size());
            result.put("failedCount", failedFiles.size());
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除商品图片
     */
    @DeleteMapping("/deleteImage")
    public Result<String> deleteProductImage(@RequestParam("imageUrl") String imageUrl) {
        try {
            // 验证用户权限（可选：检查图片是否属于当前用户）
            Map<String, Object> claims = ThreadLocalUtil.get();
            if (claims == null || claims.get("id") == null) {
                return Result.error("用户未登录");
            }
            
            ossService.deleteFile(imageUrl);
            return Result.success("图片删除成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("图片删除失败: " + e.getMessage());
        }
    }
}
